extends Control



const ShopColumn = preload("res://tool/page/shop/ShopColumn.tscn")

onready var name_input = $addModal/VBoxContainer/name/LineEdit

var edit_data = null


func _ready():	
	state_update()
	
	$addModal.visible = false
	pass 



func state_update():
	var box = $table/ScrollContainer/VBoxContainer
	
	for child in box.get_children():
		child.queue_free()
		
	for data in DataSource.get_data_list(DataSource.shop):
		var ui_item = ShopColumn.instance()
		ui_item.set_data(data)
		box.add_child(ui_item)
		
		ui_item.connect("delete", self, "_on_delete")
		ui_item.connect("edit", self, "_on_edit")
		ui_item.connect("addShop", self, "_on_addShop")
		

func _on_addBtn_button_up():
	edit_data = null
	$addModal.visible = true
	state_update_modal()


func _on_cancel_button_up():
	$addModal.visible = false


func _on_addOk_button_up():
	# 校验数据
	
	# 读取数据
	var drama_data = {
		"name": name_input.text,
	}
	
	if !drama_data["name"]:
		MainTool.toast_info("名称不能为空")
		return
	
	if edit_data:
		drama_data["id"] = edit_data["id"]
		DataSource.update_data(DataSource.shop, drama_data)
	else:
		DataSource.add_data(DataSource.shop, drama_data)	
	
	$addModal.visible = false
	state_update()


func state_update_modal():
	if edit_data:
		# 存在编辑数据
		name_input.text = edit_data["name"]
		
		$addModal/modalTitle.text = "编辑商店：%s" % [edit_data["name"]]
		$addModal/btns/ok.text = "确认"
		
	else:
		$addModal/modalTitle.text = "添加商店"
		$addModal/btns/ok.text = "确认"


func _on_delete(data):
	MainTool.confirm("你是否确认删除商店:%s" % data["name"], self, "_on_del_ok", null, data["id"])
	


func _on_del_ok(id):
	DataSource.delete_data_by_id(DataSource.shop, id)
	state_update()
	

func _on_edit(data):
	edit_data = data
	$addModal.visible = true
	state_update_modal()


func _on_addShop(data):
	var ui = MainTool.getUILayer().add_ui("res://tool/page/shop/ShopDetails.tscn")
	ui.set_data(data)
